<?php

namespace app\api\model\room;

use app\api\model\MeetModel;
use app\api\model\MeetUserModel;
use traits\model\SoftDelete;
use think\Model;

class RoomModel extends Model
{

    // 表名
    protected $name = 'mrbs_room';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';


    // 追加属性
    protected $append = [
        //  'state_text'
    ];

    public function getLogoImageAttr($val)
    {
        return cdnurl($val);
    }


    public static function detail2($input, $day)
    {
        $item = RoomModel::where('id', $input['id'])
            ->field('*')
            ->find();


        $w = date("w", strtotime($day));
        $res = RoomTimesModel::where(['room_id' => $item['id']])->field(" time as hour, (time_stage-1)*15   as start_minute,  time_stage *15   as end_minute,concat((time_stage-1)*15,'-',time_stage*15)   as time_stage ")->select();

        $item['day'] = $day;
        $item['w'] = $w;
        $item['room_type_str'] = $item['room_type'] == 0 ? '固定' : '临时';
        // $item['weeksum'] = $week;
        $weekarray = array("日", "一", "二", "三", "四", "五", "六");
        $item['week'] = "星期" . $weekarray[$w];


        foreach ($res as $key => &$value) {
            $value['start'] = $day . " " . $value['hour'] . ":" . $value['start_minute'];
            $value['end'] = $day . " " . $value['hour'] . ":" . ($value['end_minute'] - 1) . ":59";
            $time = strtotime($value['start']);
            $time2 = strtotime($value['end']);
            $value['is_order'] = 0;
            $value['order'] = [];
            $value['is_my'] = 0;
            $value['sel'] = false;
            $value['is_overdue'] = $time2 < time() ? 1 : 0;
            $week = RoomWeekModel::where("room_id =" . $item['id'] . " and week= " . $w)->count();

            if ($week > 0) {
                if ($time2 > 0) {
                    $d = RoomOrderModel::where(['room_id' => $item['id']])->field("id,user_id,title")
                        ->where(" (( starttime <= '" . $time . "' and  endtime >= '" . $time2 . "' ) or (   endtime  >= '" . $time . "' and  endtime <= '" . $time2 . "' ))  ")->find();


                    if (!empty($d)) {
                        $value['is_order'] = 1;
                        $value['order'] = $d;

                        if ($d['user_id'] == $input['user_id']) {
                            $value['is_my'] = 1;
                        }

                    }
                }
            }

            $value['state'] = ['code' => 1, 'txt' => '可以预定'];

            if ($value['is_order'] == 1) {
                $value['state'] = ['code' => 2, 'txt' => '已经预定'];
            }
            if ($value['is_my'] == 1) {
                $value['state'] = ['code' => 3, 'txt' => '我的预定'];
            }
            if ($value['is_overdue'] == 1) {
                $value['state'] = ['code' => 0, 'txt' => '已过期'];
            }
        }

        $arrT = [];
        $list = RoomTimesModel::where(['room_id' => $item['id']])->field(" time as hour ")->group("hour")->select();

        for ($i = 0; $i < count($list); $i++) {
            $arr = [];
            for ($j = 0; $j < count($res); $j++) {
                if ($list[$i]['hour'] == $res[$j]['hour']) $arr[] = $res[$j];
            }
            $arrT[$list[$i]['hour']] = $arr;
        }
        $item['res'] = $arrT;

        $item['time_scope'] = date("H:i", strtotime($res[0]['start'])) . "--" . date("H:i", strtotime($res[count($res) - 1]['end']) + 1);
        $item['user'] = MeetUserModel::where("id", "in", $item['manager_id'])->field("id,nickname,username,avatar")->find();
        unset($item['facilities']);

        return $item;
    }

    public static function getStateArr($orderlist, $start_time, $end_time, $user_id)
    {
       //print_r($start_time . "--" . $end_time . "===>>");

        $start_time = strtotime($start_time);
        $end_time = strtotime($end_time);
        $state = ['code' => 1, 'txt' => '可以预定'];
        foreach ($orderlist as $key => $item) {
          //  print_r($orderlist);
            //在内面，左包含，右包含,全包含

            if (
                (($item["starttime"] <= $start_time) && ($item["endtime"] >= $end_time))  ||
                (($item["starttime"] >= $start_time) && ($item["endtime"] <= $end_time))  ||
           (($item["starttime"] >= $start_time) && ($item["endtime"] >= $end_time) && ($item["starttime"] <= $end_time))  ||
           (($item["starttime"] <= $start_time) && ($item["starttime"] < $end_time) && ($item["starttime"] > $start_time))
            ) {
              //  print_r(date("Y-m-d H:i:s", $item["starttime"]) . "--" . date("Y-m-d H:i:s", $item["endtime"]));
                $state = ['code' => 2, 'txt' => '已经预定', 'date' => date("Y-m-d H:i:s", $item["starttime"]) . "--" . date("Y-m-d H:i:s", $item["endtime"]), 'order' => $item];
                if($item['user_id'] == $user_id){
                    $state = ['code' => 3, 'txt' => '我的预定'];
                }
                break;
            }


        }

        if($end_time < time()){
            $state = ['code' => 0, 'txt' => '已过期'];
        }
        return $state;
    }

    public static function detail($input, $day)
    {

        $item = RoomModel::where('id', $input['id'])
            ->field('*')
            ->find();

        //获取今天所有的预定
        $orderList = MeetModel::where(['room_id' => $item['id']])->field("id,user_id,title, UNIX_TIMESTAMP(start_time) as starttime, UNIX_TIMESTAMP(end_time) as endtime")
            ->where("  UNIX_TIMESTAMP(start_time) >  '" . strtotime($day) . "' and  UNIX_TIMESTAMP(end_time) <  '" . strtotime($day . " 23:23:59") . "'    ")->select();

        $list = RoomTimesModel::where(['room_id' => $item['id']])->field(" time as hour,time_stage ")->group("hour")->select();
        $arrT = [];
        $end_time = "";
        for ($i = 0; $i < count($list); $i++) {
            $arr = [];
            for ($j = 0; $j < 4; $j++) {
                $arr[$j]['start_time'] = $day . " " . $list[$i]['hour'] . ":" . $j * 15 . ":00";
                $arr[$j]['end_time'] = date("Y-m-d H:i:s", strtotime( $day . " " . $list[$i]['hour'] . ":" . ( ($j + 1) * 15  < 60 ? ($j + 1) * 15 : 59 .":59" )));
                $arr[$j]['sel'] = false;
                $arr[$j]['state'] = RoomModel::getStateArr($orderList, $arr[$j]['start_time'], $arr[$j]['end_time'],$input['user_id']);
                $end_time = $arr[$j]['end_time'] ;
            }
            $arrT[$list[$i]['hour']] = $arr;
        }

        $item['res'] = $arrT;
        $item['time_scope'] = date("H:i", strtotime($list[0]['hour'])) . "--" . date("H:i",  strtotime($end_time)+1);
        $item['edifice'] =  RoomEdificeModel::where('id', $item['edifice_id'])->field('*')->find();
        $item['manager_name'] =  MeetUserModel::where('id', $item['manager_id'])->value("nickname");

        return $item;
    }
}
